package com.evan.uyclub.HomeFragment;


import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.evan.uyclub.Bizhi.ActivityBizhi;
import com.evan.uyclub.GameBa.Game;
import com.evan.uyclub.Other.BrowserActivity;
import com.evan.uyclub.Other.Utlis;
import com.evan.uyclub.R;
import com.evan.uyclub.Touxiang.ActivityTouxiang;
import com.evan.uyclub.TwoTool.MusicActivity;
import com.google.android.exoplayer2.util.Log;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sdsmdg.tastytoast.TastyToast;
import com.skydoves.elasticviews.ElasticCardView;
import com.tapadoo.alerter.Alerter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * @noinspection ALL
 */
public class HomeFragment extends LazyFragment {
    ObjectAnimator objectAnimator;
    private ImageView home_cuo, home_dui;
    private View view;
    private TextView mrtw, jhbug, kuaiyong, home_copy, cuo_text, dui_text;
    private ImageView text_copy, like, unlike, copy;
    private ImageView home_img;
    private LinearLayout Home_bz, Home_tx, Home_yx, Home_yy, user_fank, open_qq_group;
    private String qqNum = "983751538";
    private String myqq, qunkey;
    private ElasticCardView home_card;

    /*@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        return view; //返回view
    }*/

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View views) {
        view = views;
    }

    @Override
    protected void initData() {
        initRequestData();
        initHomeImgData();
    }

    @Override
    protected void initEvent() {
        initUI();
    }

    public void joinQQ() {
        try {
            //第二种方式：可以跳转到添加好友，如果qq号是好友了，直接聊天
            String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + myqq;//uin是发送过去的qq号码
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (Exception e) {
            e.printStackTrace();
            TastyToast.makeText(getContext(), "请安装QQ", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
        }
    }

    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D" + qunkey));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    private void initRequestData() {
        if (!Utlis.isVPNConnected(getContext())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL("https://v1.hitokoto.cn/?encode=text");
                        URLConnection urlConnection = url.openConnection();
                        InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        String copy = bufferedReader.readLine();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 更新UI的操作代码
                                //比如更新TextView显示的内容
                                home_copy.setText(copy);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        copy = view.findViewById(R.id.copy);
        copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //更改src
                text_copy.setImageDrawable(getActivity().getDrawable(R.drawable.fuzhi_off));
                //获取剪贴板管理器：
                String datas = home_copy.getText().toString().trim();
                ClipboardManager copyKey = (ClipboardManager) requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", datas);
                // 将ClipData内容放到系统剪贴板里。
                copyKey.setPrimaryClip(mClipData);
                Alerter.create(requireActivity()).setTitle("复制到剪切板喽~").setText(datas).setBackgroundColorRes(R.color.fbutton_color_emerald).setDuration(1500).show();
            }
        });
    }

    public void initHomeImgData() {
        if (!Utlis.isVPNConnected(getContext())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL("https://uyclouds.com/uyapi/file_text.php?keeper=3487297072&api=488588&title=homedate");
                        URLConnection urlConnection = url.openConnection();
                        InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        String copy = bufferedReader.readLine();
                        Log.e("TAG", copy);
                        JsonHome(copy);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void JsonHome(String copy) throws JSONException {
        JSONObject jsonObject = new JSONObject(copy);
        String imgurl = jsonObject.getString("imgurl");
        String weburl = jsonObject.getString("weburl");
        myqq = jsonObject.getString("myqq");
        qunkey = jsonObject.getString("qunkey");
        home_card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                intent3.putExtra("网址", weburl);
                intent3.setClass(requireActivity(), BrowserActivity.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Glide.with(requireActivity()).load(imgurl).error(R.mipmap.ic_load).into(home_img);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void initUI() {
        //获取每日同问对错图标
        like = view.findViewById(R.id.like);
        home_dui = view.findViewById(R.id.home_dui);
        //获取其对，错数量
        cuo_text = view.findViewById(R.id.cuo_text);
        dui_text = view.findViewById(R.id.dui_text);
        //轮播图
        home_img = view.findViewById(R.id.home_img);
        home_card = view.findViewById(R.id.home_card);

        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(home_card, "alpha", 0f, 1f);
        objectAnimator.setDuration(1200);
        objectAnimator.start();

        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                home_dui.setImageDrawable(getActivity().getDrawable(R.drawable.img_1dui));
                TastyToast.makeText(requireActivity(), "祝一生平安。", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
            }
        });

        unlike = view.findViewById(R.id.unlike);
        home_cuo = view.findViewById(R.id.home_cuo);

        unlike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                home_cuo.setImageDrawable(getActivity().getDrawable(R.drawable.img_1cuo));
                TastyToast.makeText(requireActivity(), "请你开心哦！", TastyToast.LENGTH_LONG, TastyToast.ERROR);
            }
        });

        //头像壁纸功能
        Home_bz = view.findViewById(R.id.home_bz);
        Home_bz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                // intent3.setClass(getActivity(), WallpaperActivity.class);
                intent3.setClass(getActivity(), ActivityBizhi.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        Home_tx = view.findViewById(R.id.Home_tx);
        Home_tx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                //  intent3.setClass(getActivity(), AvatarActivity.class);
                intent3.setClass(getActivity(), ActivityTouxiang.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        Home_yx = view.findViewById(R.id.Home_yx);
        Home_yx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                //  intent3.setClass(getActivity(), AvatarActivity.class);
                intent3.setClass(getActivity(), Game.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        Home_yy = view.findViewById(R.id.Home_yy);
        Home_yy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                intent3.setClass(getActivity(), MusicActivity.class);
                //intent3.setClass(getActivity(), NeteaseSongActivity.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        user_fank = view.findViewById(R.id.user_fank);
        user_fank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                intent3.putExtra("网址", "https://support.qq.com/products/410589");
                intent3.setClass(getActivity(), BrowserActivity.class);
                //  intent3.setClass(getActivity(), AvatarActivity.class);
                startActivity(intent3);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        open_qq_group = view.findViewById(R.id.open_qq);
        open_qq_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                joinQQGroup("4wHKnqMDHP0xdrk73XK0RaUs699QJHGH");
            }
        });
        //复制进行动画
        //获取首页文案文本和复制控件
        home_copy = view.findViewById(R.id.home_copy);
        text_copy = view.findViewById(R.id.text_copy);
        //实现回弹效果，支持带列表的。
        SmartRefreshLayout home_smart = (SmartRefreshLayout) view.findViewById(R.id.home_smart);
        home_smart.setEnableLoadMore(true);
        home_smart.setEnablePureScrollMode(true);
        //设置对应xml界面的字体
        TextView up_title = view.findViewById(R.id.up);
        TextView cloud_title = view.findViewById(R.id.cloud);
        up_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        cloud_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        //动起来  ---不能写，因为一打开首页这些动画就开始执行
        objectAnimator = objectAnimator.ofFloat(up_title, "translationX", -100f, 0f);
        objectAnimator.setDuration(3000);
        objectAnimator.start();
        objectAnimator = objectAnimator.ofFloat(cloud_title, "translationX", -60f, 0f);
        objectAnimator.setDuration(3000);
        objectAnimator.start();
        LinearLayout sy_ss = (LinearLayout) view.findViewById(R.id.sy_ss);
        objectAnimator = objectAnimator.ofFloat(sy_ss, "translationX", 150f, 0f);
        objectAnimator.setDuration(3000);
        objectAnimator.start();
        mrtw = view.findViewById(R.id.mrtw);
        jhbug = view.findViewById(R.id.jhbug);
        kuaiyong = view.findViewById(R.id.kuaiyong);
        String hometext = "english.ttf";
        //设置字体
        mrtw.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), hometext));
        jhbug.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), hometext));
        kuaiyong.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), hometext));
    }

}